<script setup>
	//触底触发异步请求，实现分页查询的下拉选择组件
	import { ref, getCurrentInstance, watch } from 'vue';
	const { proxy } = getCurrentInstance();
	const emit = defineEmits(['selectChange']);
	const props = defineProps({
		//placeholder提示
		placeholder: {
			type: String,
			default: '',
		},
		//是否可搜索
		showSearch: {
			type: Boolean,
			default: true,
		},
		//是否允许清空
		allowClear: {
			type: Boolean,
			default: true,
		},
		//是否多选
		multiple: {
			type: Boolean,
			default: false,
		},
		// 接口地址
		url: {},

		//分页数据
		page: {
			type: Object,
			default: () => {
				return { page: 1, limit: 15, total: 0 };
			},
		},

		//选择获取的数据的key
		valueName: {
			type: String,
			default: 'ID',
		},
		//显示的字段
		labelName: {
			type: String,
			default: '',
		},
		//显示的子字段
		labelName2: {
			type: String,
			default: '',
		},
		//筛选条件
		searchDta: {
			type: Object,
			default: () => {
				return {};
			},
		},
		//搜索的lstKey，有些搜索值需要特殊处理，例如lstKey里面包含模糊查询和精确查询
		LstKey: {
			type: Array,
			default: () => []
		},
		// url的参数
		urlParams: {
			type: String,
			default: '',
		},

		//编辑时，已选的数据值
		selectVal: {
			type: String,
			default: ''
		},
		//编辑时，已选的数据lable--编辑单选时用来做搜索值，多选用来加进数据列表
		selectLable: {
			type: String,
			default: ''
		},
		//编辑时，已选的数据lable-多选用来加进数据列表-（可选）
		selectLable2: {
			type: String,
			default: ''
		},
		
		//搜索框筛选的字段
		selectName: {
			type: [String],
			default: 'Keyword',
		},
		//请求方式
		method: {
			type: String,
			default: 'post',
		},

		//是否开启全选
		isAllSelect: {
			type: Boolean,
			default: true,
		},
		//是否自动请求数据
		isAuto: {
			type: Boolean,
			default: false,
		},
		//是否禁用
		isDisabled: {
			type: Boolean,
			default: false
		}
	});

	const pageData = ref(JSON.parse(JSON.stringify(props.page))); //分页数据
	const searchDtas = ref(JSON.parse(JSON.stringify(props.searchDta)));//筛选条件
	const value = ref(JSON.parse(JSON.stringify(props.selectVal))); //选择的值
	const loading = ref(false); //laoding
	const list = ref([]); //数据列表
	const isMore = ref(false); //是否请求完全部数据
	const Keyword = ref('');
	const backupKeyword = ref(''); //备份的Keyword

	const checkboxValue = ref(false); //全选
	const isIndeterminate = ref(true); //复选框开启半选状态

	watch(value, (newValue) => {
		if (!newValue) {
			Keyword.value = '';
			backupKeyword.value = '';
			restDta();
			change();
		}
		//控制全选
		if(!props.multiple) return
		if (newValue.length === 0) {
			checkboxValue.value = false;
			isIndeterminate.value = false;
		} else if (newValue.length === list.value.length) {
			checkboxValue.value = true;
			isIndeterminate.value = false;
		} else {
			checkboxValue.value = true;
			isIndeterminate.value = true;
		}
	});
	//监听已选值的变化
	watch(()=>props.selectVal, (newValue) => {
		if(!newValue) {
			value.value = ''
		}
	});
	
	//初始化数据
	function restDta() {
		pageData.value.page = 1;
		isMore.value = false;
		getData();
	}

	//选择时触发
	function change(data) {
		if (!props.multiple) {
			//单选
			let items = list.value.filter((item) => {
				//根据回调的ID，找出对应的数据
				return item[props.valueName] == data;
			});
			if (items.length > 0) {
				//处理选择的数据
				backupKeyword.value = `${props.labelName2 ? `${items[0][props.labelName2]} ` : ''}${items[0][props.labelName]}`; //备份选择的搜索条件
				emit('selectChange', items[0]);
			} else {
				emit('selectChange', {});
			}
		} else {
			//多选
			let lists = [];
			data.forEach((item) => {
				list.value.forEach((item2) => {
					if (item == item2[props.valueName]) {
						lists.push(item2);
					}
				});
			});
			emit('selectChange', lists);
		}
	}

	//搜索文本值变化时触发
	function searchFun(data) {
		let datas = data.split(' ');
		Keyword.value = datas[1] ? datas[1] : datas[0];
		restDta();
	}

	//点击下拉选择框时触发
	function selectBoxClick() {
		//如果已经选过值，则重置搜索条件，否则输入框的值和返回的数据不一致
		Keyword.value = JSON.parse(JSON.stringify(backupKeyword.value));
		searchFun(Keyword.value);
		//监听触底事件
		proxy.$common.selectLoadmore(() => {
			getData();
		});
	}

	//多选
	function hanldeChange(v) {
		isIndeterminate.value = false;
		value.value = [];
		if (v) {
			list.value.forEach((item) => {
				value.value.push(item[props.valueName]);
			});
		}
	}

	//自定义搜索条件
	function searchMethod(text, optionProps) {
		return true;
	}

	//获取下拉选择框数据
	function getData() {
		let params = {}; //搜索条件
		if (props.selectName == 'Keyword') {
			params[props.selectName] = Keyword.value;
		} else {
			searchDtas.value[props.selectName] = Keyword.value;
			params = proxy.$common.searchPars(searchDtas.value);

			if (props.LstKey && props.LstKey.length > 0) {
				params.LstKey = [...params.LstKey, ...props.LstKey]
			}
		}

		const page = {
			page: pageData.value.page,
			limit: pageData.value.limit,
		};
		if (props.method == 'post') params = { ...params, ...page }; //合并分页搜索添加
		if (loading.value || isMore.value) return; //loading
		loading.value = true;
		props.url(params, props.urlParams).then((res) => {
			const datas = res.data || [];
			if (pageData.value.page == 1) list.value = [];

			if (props.multiple) {
				//处理多选数据
				if (pageData.value.page == 1 && props.selectVal) {
					//把已选的数据赋值进列表
					let labelName = props.selectLable.split(',');
					let valueName = props.selectVal.split(',');
					valueName.forEach((item, index) => {
						let listItem = {};
						listItem[props.labelName] = labelName[index];
						listItem[props.valueName] = item;
						if (props.selectLable) {
							let labelName2 = selectLable?.split(',');
							listItem[props.labelName2] = labelName2[index];
						}
						list.value.push(listItem);
					});
				}

				datas.forEach((item) => {
					if (props.selectVal) {
						//过滤掉多选时已有的数据
						let valueName = props.selectVal.split(',')
						let isFig = false;
						valueName.forEach((item2) => {
							if (item[props.valueName] == item2) isFig = true;
						});
						if (!isFig) list.value.push(item);
					} else {
						list.value.push(item);
					}
				});
			} else {
				list.value = list.value.concat(datas);
			}

			pageData.value.page++; //页码++
			if (res.totalCount == list.value.length || datas.length != pageData.value.limit) {
				//如果总数==list总条数，或者返回的条数不等于每页请求的条数 说明没有更多了
				isMore.value = true;
			} else {
				isMore.value = false;
			}
			loading.value = false;
		}).catch((err) => {
			loading.value = false;
		});
	}

	if (!props.multiple) {
		//编辑、单项的时候设置默认搜索条件
		value.value = props.selectVal
		Keyword.value = props.selectLable
		backupKeyword.value = props.selectLable
	}else {
		//多选
		value.value = props.selectVal.split(',')
	}
	
	if(props.isAuto) {
		restDta(); //初始化数据
	}
</script>
<template>
	<lay-select :disabled="isDisabled" :placeholder="placeholder" :searchMethod="searchMethod" v-model="value" :multiple="multiple" :allowClear="allowClear" @click="selectBoxClick" @search="searchFun" @change="change" :showSearch="showSearch" contentClass="pol-select">
		<template #header v-if="multiple && isAllSelect">
			<div style="padding: 10px 10px 0 10px">
				<lay-checkbox v-model="checkboxValue" skin="primary" :isIndeterminate="isIndeterminate" @change="hanldeChange">全选</lay-checkbox>
			</div>
		</template>
		<template v-for="(item, index) in list" :key="index">
			<lay-select-option :value="item[valueName]">{{ labelName2 ? `${item[labelName2]} ` : '' }}{{ item[labelName] }}</lay-select-option>
		</template>
		<template #footer>
			<lay-button disabled :loading="true" size="sm" fluid v-if="loading">加载中...</lay-button>
			<div class="text-center text-gray padding text-md" v-if="list.length == 0 && !loading">暂无数据</div>
			<div class="text-center text-gray padding text-md" v-if="isMore && list.length > 0">没有更多了</div>
		</template>
	</lay-select>
</template>

<style lang="scss" scoped></style>